package com.moli.filter;

import com.alibaba.fastjson.JSON;
import com.moli.domain.ResponseResult;
import com.moli.domain.entity.LoginUser;
import com.moli.enums.AppHttpCodeEnum;
import com.moli.utils.JwtUtil;
import com.moli.utils.RedisCache;
import com.moli.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author： XC
 * @Date： 2023-06-08 8:46
 * @Description： 权限验证过滤器
 */
@Component
//默认的过滤器接口，可能会存在一个请求过来，过滤器被调用多次，所以使用spring自带的过滤器，保证只会调用一次 一次请求，只会经过这个过滤器一次
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

	@Autowired
	private RedisCache redisCache;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		//1.获取请求头中的token
		String token = request.getHeader("token");
		if (!StringUtils.hasText(token)) {
			//说明该接口不需要登录  直接放行  由下一过滤器进行拦截
			filterChain.doFilter(request, response);
			return;
		}
		//2.解析token，获取userid
		Claims claims = null;
		try {
			claims = JwtUtil.parseJWT(token);
		} catch (Exception e) {
			e.printStackTrace();
			//token超时  token非法
			//响应告诉前端需要重新登录
			ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
			WebUtils.renderString(response, JSON.toJSONString(result));
			return;
		}
		//获取用户id
		String userId = claims.getSubject();
		//3.从redis中获取用户信息（token中只有用户id，要获取全部信息，还得从redis中取）
		LoginUser loginUser = redisCache.getCacheObject("login:" + userId);
		//如果获取不到，redis没有这个用户信息
		if (Objects.isNull(loginUser)) {
			//说明登录过期  提示重新登录
			ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
			WebUtils.renderString(response, JSON.toJSONString(result));
			return;
		}
		//4.存入SecurityContextHolder
		//TODO 获取权限信息封装到Authentication中
		UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
		SecurityContextHolder.getContext().setAuthentication(authenticationToken);
		//对请求进行放行
		filterChain.doFilter(request, response);
	}


}